const express = require('express');
const router = express.Router();
const { User } = require('../database/models');
const { 
  authenticate,
  authorize,
  asyncHandler 
} = require('../middleware');
const { 
  validate,
  paginationValidation
} = require('../middleware/validation');

// 获取用户列表（仅管理员）
router.get('/', 
  authenticate,
  authorize('admin'),
  validate(paginationValidation, 'query'),
  asyncHandler(async (req, res) => {
    const { page, pageSize } = req.query;
    const { role, isActive, search } = req.query;

    // 构建查询条件
    const query = {};
    
    if (role) {
      query.role = role;
    }
    
    if (isActive !== undefined) {
      query.isActive = isActive === 'true';
    }
    
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { phone: { $regex: search, $options: 'i' } },
        { email: { $regex: search, $options: 'i' } }
      ];
    }

    // 计算分页
    const skip = (page - 1) * pageSize;

    // 查询用户
    const [users, total] = await Promise.all([
      User.find(query)
        .select('-password')
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(pageSize),
      User.countDocuments(query)
    ]);

    const totalPages = Math.ceil(total / pageSize);

    res.status(200).json({
      success: true,
      message: '获取用户列表成功',
      code: 200,
      data: {
        data: users,
        pagination: {
          total,
          page,
          pageSize,
          totalPages
        }
      }
    });
  })
);

// 获取指定用户信息（仅管理员）
router.get('/:userId', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { userId } = req.params;

    // 验证ObjectId格式
    if (!userId.match(/^[0-9a-fA-F]{24}$/)) {
      return res.status(400).json({
        success: false,
        message: '用户ID格式无效',
        code: 400,
        data: null
      });
    }

    const user = await User.findById(userId).select('-password');
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 404,
        data: null
      });
    }

    res.status(200).json({
      success: true,
      message: '获取用户信息成功',
      code: 200,
      data: user
    });
  })
);

// 获取维修员列表
router.get('/maintainers/list', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { isActive = true } = req.query;

    const maintainers = await User.find({
      role: 'maintainer',
      isActive: isActive === 'true'
    })
    .select('name phone email specialties experience rating completedOrders isActive')
    .sort({ rating: -1, completedOrders: -1 });

    res.status(200).json({
      success: true,
      message: '获取维修员列表成功',
      code: 200,
      data: maintainers
    });
  })
);

// 更新用户状态（仅管理员）
router.put('/:userId/status', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { userId } = req.params;
    const { isActive } = req.body;

    if (typeof isActive !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: 'isActive必须是布尔值',
        code: 400,
        data: null
      });
    }

    const user = await User.findByIdAndUpdate(
      userId,
      { isActive },
      { new: true, runValidators: true }
    ).select('-password');

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 404,
        data: null
      });
    }

    res.status(200).json({
      success: true,
      message: `用户已${isActive ? '激活' : '禁用'}`,
      code: 200,
      data: user
    });
  })
);

// 更新用户角色（仅管理员）
router.put('/:userId/role', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { userId } = req.params;
    const { role } = req.body;

    if (!['user', 'maintainer', 'admin'].includes(role)) {
      return res.status(400).json({
        success: false,
        message: '角色只能是 user、maintainer 或 admin',
        code: 400,
        data: null
      });
    }

    const user = await User.findByIdAndUpdate(
      userId,
      { role },
      { new: true, runValidators: true }
    ).select('-password');

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 404,
        data: null
      });
    }

    res.status(200).json({
      success: true,
      message: '用户角色更新成功',
      code: 200,
      data: user
    });
  })
);

// 重置用户密码（仅管理员）
router.put('/:userId/reset-password', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { userId } = req.params;
    const { newPassword } = req.body;

    if (!newPassword || newPassword.length < 6) {
      return res.status(400).json({
        success: false,
        message: '新密码至少需要6个字符',
        code: 400,
        data: null
      });
    }

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 404,
        data: null
      });
    }

    user.password = newPassword;
    await user.save();

    res.status(200).json({
      success: true,
      message: '密码重置成功',
      code: 200,
      data: null
    });
  })
);

// 删除用户（仅管理员）
router.delete('/:userId', 
  authenticate,
  authorize('admin'),
  asyncHandler(async (req, res) => {
    const { userId } = req.params;
    const currentUser = req.user;

    // 不能删除自己
    if (userId === currentUser._id.toString()) {
      return res.status(400).json({
        success: false,
        message: '不能删除自己的账户',
        code: 400,
        data: null
      });
    }

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在',
        code: 404,
        data: null
      });
    }

    // 检查用户是否有关联的工单
    const { Order } = require('../database/models');
    const orderCount = await Order.countDocuments({
      $or: [
        { userId: userId },
        { maintainerId: userId }
      ]
    });

    if (orderCount > 0) {
      return res.status(400).json({
        success: false,
        message: '该用户有关联的工单，无法删除',
        code: 400,
        data: null
      });
    }

    await User.findByIdAndDelete(userId);

    res.status(200).json({
      success: true,
      message: '用户删除成功',
      code: 200,
      data: null
    });
  })
);

module.exports = router;
